package com.tb.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tb.async.MailTask;
import com.tb.mapper.UserMapper;
import com.tb.model.Follow;
import com.tb.model.User;
import com.tb.model.UserExample;
import com.tb.util.MyConstant;
import com.tb.util.MyUtils;
import com.tb.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FollowService followService;

    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private JavaMailSender javaMailSender;

    /* 登录 */
    public Map<String, Object> loginCheck(String email, String password, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();

        // 校验用户名和密码是否正确
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andEmailEqualTo(email);
//        criteria.andPasswordEqualTo(password);
        List<User> users = userMapper.selectByExample(userExample);
        if (users.isEmpty()||!users.get(0).getPassword().equals(password)) {
            map.put("error", "用户名或密码错误");
            return map;
        }
        User logier = users.get(0);
        // 校验用户帐号是否激活
        if (logier.getActivateStatus() == 0) {
            map.put("error", "您的帐号还没有激活,请前往邮箱激活");
            // 发送邮件
            taskExecutor.execute(new MailTask("" + logier.getId(), email, javaMailSender, MyConstant.MAIL_ACTIVATE));
            return map;
        }
        //验证通过,信息填入map传到前端，设置cookie
        map.put("user", logier);

        return map;
    }

    /* 注册 */
    public Map<String, String> register(String username, String email, String password) {
        Map<String, String> map = new HashMap<>();

        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andEmailEqualTo(email);
        List<User> users = userMapper.selectByExample(example);

        //数据库已有账号
        if (users.size() > 0) {
            int activationState = users.get(0).getActivateStatus();
            //但是未激活
            if (activationState == 0) {
                //删除旧帐号
                userMapper.deleteByPrimaryKey(users.get(0).getId());
                //已注册
            } else if (activationState == 1) {
                map.put("regi-email-error", "该邮箱已注册");
                return map;
            }
        }


        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        // 构造user，设置未激活
        user.setActivateStatus((byte) 0);
        user.setTime(new Date().getTime());
        user.setName(username);
        //设置默认头像
        user.setAvatarUrl(MyConstant.AVATAR_URL + MyUtils.random(MyConstant.AVATAR_START, MyConstant.AVATAR_END) + MyConstant.AVATAR_SUFFIX);

        // 向数据库插入记录
        userMapper.insertSelective(user);

        // 设置默认关注用户
        Follow follow = new Follow();
        follow.setFromId(user.getId());
        follow.setTime(new Date().getTime());
        follow.setToId(1);
        followService.addRecord(follow);

        // 发送激活邮件
        taskExecutor.execute(new MailTask("" + user.getId(), user.getEmail(), javaMailSender, MyConstant.MAIL_ACTIVATE));

        map.put("ok", "注册完成");
        return map;
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //清空Cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            cookie.setValue(null);
            cookie.setMaxAge(-1);
            response.addCookie(cookie);
        }
    }

    public PageInfo<User> getUserListByPage(Integer pageId) {

//        int limit = (pageId - 1) * 15;
//        int offset = 15;
        PageHelper.startPage(pageId, MyConstant.PAGE_SIZE_USER);
        List<User> userList = userMapper.selectByExample(null);
        return new PageInfo<>(userList);
    }

    public User getUserById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    public int getCount() {
        return userMapper.countByExample(null);
    }

    public void transferSuperAdmin(int myId, int toId) {
        //将目标设为超级管理员
        User my = userMapper.selectByPrimaryKey(myId);
        my.setRole((byte) 0);
        userMapper.updateByPrimaryKeySelective(my);
        //将自己设为普通群众
        User to = userMapper.selectByPrimaryKey(toId);
        to.setRole((byte) 2);
        userMapper.updateByPrimaryKeySelective(to);
    }

    public void setManager(int userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        user.setRole((byte) 1);
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void setUser(int userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        user.setRole((byte) 2);
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void deleteUser(int userId) {
        userMapper.deleteByPrimaryKey(userId);
    }

    public void activateUser(int userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        user.setActivateStatus((byte) 1);
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void modify(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    public boolean changePsw(int id, String oldPsw, String newPsw) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user.getPassword().equals(oldPsw)) {
            user.setPassword(newPsw);
            userMapper.updateByPrimaryKeySelective(user);
            // 发送密码修改提醒邮件
            taskExecutor.execute(new MailTask("" + user.getId(), user.getEmail(), javaMailSender, MyConstant.MAIL_CHANGE_PASSWORD));
            return true;
        }
        return false;
    }

    /**
     * 更新头像 返回新的头像地址
     *
     * @param userId
     * @param file
     * @param request
     * @return 新的头像地址
     */
    public Response modifyAvatarFile(int userId, MultipartFile file, HttpServletRequest request) throws IOException {
        // 包含原始文件名的字符串
        String fi = file.getOriginalFilename();
        // 提取文件拓展名
        String fileNameExtension = fi.substring(fi.indexOf("."));
        boolean typeIsRight = fileNameExtension.equals(".png") || fileNameExtension.equals(".jpeg") || fileNameExtension.equals(".gif") || fileNameExtension.equals(".jpg");
        if (typeIsRight) {
            // 生成云端的真实文件名
            String remoteFileName = "/image/avatar/avatar-" + userId + fileNameExtension;
            // 开始上传
            file.transferTo(new File(request.getSession().getServletContext().getRealPath("/") + remoteFileName));
            //更新数据库
            User user = userMapper.selectByPrimaryKey(userId);
            user.setAvatarUrl(remoteFileName);
            userMapper.updateByPrimaryKeySelective(user);
            return new Response(1, "上传成功", remoteFileName);
        } else {
            return new Response(0,"请上传图片文件","");
        }

    }
}
